const fs = require('fs');
const https = require('https');
const path = require('path');

// 创建图片下载函数
function downloadImage(url, filename) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filename);

    https.get(url, (response) => {
      response.pipe(file);

      file.on('finish', () => {
        file.close();
        console.log(`✅ Downloaded: ${filename}`);
        resolve();
      });
    }).on('error', (err) => {
      fs.unlink(filename, () => { }); // 删除未完成的文件
      console.error(`❌ Error downloading ${filename}:`, err.message);
      reject(err);
    });
  });
}

// 要下载的图片列表
const images = [
  // 轮播图
  {
    url: 'https://picsum.photos/id/1018/1200/400',
    filename: 'banner1.jpg',
    description: '智能家电轮播图'
  },
  {
    url: 'https://picsum.photos/id/1019/1200/400',
    filename: 'banner2.jpg',
    description: '夏季清凉特惠轮播图'
  },
  {
    url: 'https://picsum.photos/id/1021/1200/400',
    filename: 'banner3.jpg',
    description: '品质生活轮播图'
  },
  {
    url: 'https://picsum.photos/id/1022/1200/400',
    filename: 'banner4.jpg',
    description: '数码新品轮播图'
  },

  // 产品卡片图片
  {
    url: 'https://picsum.photos/id/26/300/300',
    filename: 'product1.png',
    description: '品质家居产品图'
  },
  {
    url: 'https://picsum.photos/id/3/300/300',
    filename: 'product2.png',
    description: '精致美妆产品图'
  },
  {
    url: 'https://picsum.photos/id/36/300/300',
    filename: 'product3.png',
    description: '品质五金产品图'
  },
  {
    url: 'https://picsum.photos/id/24/300/300',
    filename: 'product4.png',
    description: '超值百货产品图'
  }
];

// 开始下载所有图片
async function downloadAllImages() {
  console.log('🚀 Starting image downloads...');

  for (const image of images) {
    const filePath = path.join(__dirname, image.filename);
    console.log(`📥 Downloading: ${image.description} (${image.filename})`);

    try {
      await downloadImage(image.url, filePath);
    } catch (error) {
      console.error(`Failed to download ${image.filename}`);
    }
  }

  console.log('✨ All downloads completed!');
}

// 执行下载
downloadAllImages();
